from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from django.core.exceptions import ObjectDoesNotExist
from .models import Host, DataCenter, City, HostStatistics
from .serializers import HostSerializer, DataCenterSerializer, CitySerializer, HostStatisticsSerializer
import subprocess
import platform
from django.contrib.auth import make_password

class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_active = False
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class HostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = HostStatistics.objects.all()
    serializer_class = HostStatisticsSerializer


def ping_host(request, pk):
    try:
        host = Host.objects.get(pk=pk)
        param = '-n' if platform.system().lower() == 'windows' else '-c'
        command = ['ping', param, '1', host.ip_address]
        
        # 执行ping命令
        proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = proc.communicate()
        
        # 解析输出结果
        if proc.returncode == 0:
            return Response({"status": "reachable", "output": out.decode('utf-8')})
        else:
            return Response({"status": "unreachable", "error": err.decode('utf-8')})
    except ObjectDoesNotExist:
        return Response({"error": "Host not found"}, status=status.HTTP_404_NOT_FOUND)

# Create your views here.
